package com.fantasy.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
 * 
 * @author heqichang
 * 客户端
 * */
public class ThreadSocketClient extends Thread{
	
	static Socket socket;
	
	public void run()
	{
		try {
			BufferedReader br2=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String read=new String();
			
			//接受来自服务端的姓名信息
			String name=br2.readLine();
			
			//接受来自服务端的信息
			while(true)
			{
				read=br2.readLine();
				System.out.println(name+"说："+read);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	 
	
	public static void main(String[] args) throws IOException
	{
		socket=new Socket("127.0.0.1",9999);
		
		BufferedReader inputName=new BufferedReader(new InputStreamReader(System.in));
		
		System.out.print("已连接上服务端，请输入你的姓名：");
		String name=inputName.readLine();
		
		//启动一个线程进行接收服务端信息
		ThreadSocketClient thread=new ThreadSocketClient();
		thread.start();
		
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw=new PrintWriter(socket.getOutputStream());
		
		//发送给服务端客户端的姓名信息
		pw.println(name);
		
		String info=new String();
		
		//发送消息给服务端
		while(!info.equals("bye"))
		{
			info=br.readLine();
			pw.println(info);
			pw.flush();
		}
		
		pw.close();
		socket.close();
	}
}
